cat(sprintf("\nScript 5: Produce figures (%s)\n", f_time_gmt()))

# Load functions ---------------------------------------------------------------

theme_set(theme_bw() + theme(panel.grid.minor.x = element_blank(),
                             legend.position = "bottom"))

hr_raw <- readRDS(here("proc", "hr.rds"))[
  , treatment_lbl := fifelse(treatment == 1, "Pos keyed", "Neg keyed")
]

wordings <- fread(here("data", "hr", "question_wordings.csv"))



# Figures 1, B1, B2: % agreement with statements in H&R, by education ----------

# Function that creates plot for one question

education_plot <- function(question, tag = NULL, save = T){
  dt_plot <- hr_raw[
    q == question,
  ][
    , agree := fifelse(newdv == 1, 1L, 0L, na = 0L) # note: keep NA as 0
  ][
    , .(pct_agree = mean(agree), n = .N), .(treatment_lbl, ed4)
  ][
    , me :=  1.96 * sqrt(pct_agree * (1 - pct_agree) / n)
  ][
    , ":="(pct_agree_high = pct_agree + me, pct_agree_low = pct_agree - me)
  ][] |> 
    na.omit()
  
  p <- ggplot(dt_plot, mapping = aes(x = ed4, 
                                     y = pct_agree * 100,
                                     ymin = pct_agree_high * 100,
                                     ymax = pct_agree_low * 100,
                                     color = treatment_lbl
  )) +
    geom_pointrange(position = position_dodge(width = 0.1)) +
    labs(x = "Education Group", y = "% Agreeing with Claim", color = NULL,
         subtitle = wordings[q == question, pos_key] |> str_wrap(48)) +
    scale_color_manual(values = c("black", "red")) +
    geom_hline(yintercept = 50, linetype = 'dashed')
  
  if (save){
    cat(sprintf("--Save figures/figure_%s_%s.png (%s)\n",
        tag, question, f_time_gmt()))
    ggsave(filename = here("figures", sprintf("figure_%s_%s.png", tag, question)),
           p, height = 4.5, width = 5, scale = .86)
  } else {
    p
  }
}

# Save four selected plots for Figure 1:

patchwork_fig1 <- wrap_plots(
  education_plot("Clinton.arms", save = F),
  education_plot("Pope.endorse", save = F),
  education_plot("Pence.vulgar", save = F),
  education_plot("Ireland.asylum", save = F)
)

cat(sprintf("--Save figures/figure_1_select_questions.png (%s)\n",
            f_time_gmt()))
ggsave(filename = here("figures", "figure_1_select_questions.png"),
       patchwork_fig1, height = 9, width = 10, scale = .86)


# Save plots for Figure B1 (false claims):

education_plot("RuPaul", "b1a")
education_plot("FBI.agent", "b1b")

# Save plots for Figure B2 (true claims):

education_plot("Beyonce.rally", "b2a")
education_plot("Clinton.deplorables", "b2b")
education_plot("FBI.director", "b2c")
education_plot("Clinton.stumbled", "b2d")
education_plot("FBI.Clinton.charges", "b2e")
education_plot("Trump.concede", "b2f")



# Figure 2: % agreement with Springfield claim by education --------------------

# Pool Cint and Bovitz data

cint <- readRDS("proc/cint.rds")
cint[, survey := "Lucid/Cint"]
bovitz <- readRDS("proc/bovitz.rds")
bovitz[, survey := "Bovitz"]
pooled <- rbind(cint, bovitz, fill = T)[
  , treatment_lbl := fifelse(treatment == 1, "Pos keyed", "Neg keyed")
]

# Calculate agreement with Springfield statement by treatment status

dt_plot_springfield <- pooled[
  q == "springfield"
][
  , agree := fifelse(newdv == 1, 1L, 0L, na = 0L) # note: keep NA as 0
][
  , .(pct_agree = mean(agree), n = .N), .(survey, treatment_lbl, ed4)
][
  , me :=  1.96 * sqrt(pct_agree * (1 - pct_agree) / n)
][
  , ":="(pct_agree_high = pct_agree + me, pct_agree_low = pct_agree - me)
][] |> 
  na.omit()

# Generate Springfield plot

p_springfield <- ggplot(dt_plot_springfield, 
                        mapping = aes(x = ed4, 
                                      y = pct_agree * 100,
                                      ymin = pct_agree_high * 100,
                                      ymax = pct_agree_low * 100,
                                      color = treatment_lbl)) +
  geom_pointrange(position = position_dodge(width = 0.1)) +
  labs(x = "Education Group", y = "% Agreeing with Claim", color = NULL,
       subtitle = 'The city manager of Springfield OH confirmed receiving credible reports of pets being eaten.') +
  scale_color_manual(values = c("black", "red")) +
  geom_hline(yintercept = 50, linetype = 'dashed') +
  facet_grid(~forcats::fct_rev(survey))

# Save plot

cat(sprintf("--Save figures/figure_2_springfield.png %s\n",
            f_time_gmt()))
ggsave(here("figures", "figure_2_springfield.png"), 
       height = 4.5, width = 9, scale = .86)



# Figure B3: Acq Bias and Education, by att checks and platform ----------------

# Estimate Cint model and plot slopes

m_cint_acqed_bychecks <- feols(newdv ~ treatment * education_num * f_mock_count, 
                               cint, cluster = ~r_id)
p_cint_acqed_bychecks <- plot_slopes(
  m_cint_acqed_bychecks, c("treatment"), c("education_num", "f_mock_count")
) +
  labs(color = "Attention checks passed", fill = "Attention checks passed",
       x = "Education", y = "Acquiescence Bias",
       subtitle = "Lucid/Cint") +
  guides(color = guide_none(), fill = guide_none()) +
  scale_color_manual(values = c("None" = "#001f3f",
                                "Some" = "#2ECC40",
                                "All"  = "#FFDC00")) +
  scale_fill_manual(values = c("None" = "#001f3f",
                               "Some" = "#2ECC40",
                               "All"  = "#FFDC00"))

# Estimate Bovitz model and plot slopes

m_bovitz_acqed_bychecks <- feols(newdv ~ treatment * education_num * f_mock_count, 
                                 bovitz, cluster = ~r_id)
p_bovitz_acqed_bychecks <- plot_slopes(
  m_bovitz_acqed_bychecks, c("treatment"), c("education_num", "f_mock_count")
) +
  labs(color = "Attention checks\npassed", fill = "Attention checks\npassed",
       x = "Education", y = "Acquiescence Bias",
       subtitle = "Bovitz") +
  scale_color_manual(values = c("None" = "#001f3f",
                                "Some" = "#2ECC40",
                                "All"  = "#FFDC00")) +
  scale_fill_manual(values = c("None" = "#001f3f",
                               "Some" = "#2ECC40",
                               "All"  = "#FFDC00")) +
  theme_bw() +
  theme(legend.position = "right")

# Save figures side by side

cat(sprintf("--Save figures/figure_b3_attention_checks.png (%s)\n",
            f_time_gmt()))
ggsave(here("figures", "figure_b3_attention_checks.png"), 
       p_cint_acqed_bychecks + p_bovitz_acqed_bychecks,
       width = 9, height = 4, scale = .86)

